<?php


namespace app\api\controller;

use app\api\model\Communication as CommunicationModel;
use app\api\model\User as UserModel;

class Communication extends Base
{

    /***
     * Desc :存储聊天记录
     * User : HAIYUN
     * Date : 2022-01-17 14:52
     */
    public function saveMessage()
    {
//        //获取用户
//        //根据token获取uid
//        $uid = $this->getCurrentTokenVar("uid");
//        //根据uid查找用户数据，判断是否存在
//        $userModel = new UserModel();
//        $user = $userModel->where("id",$uid)->find();
//        if(!$user){
//            $this->return_msg("20004","用户不存在",[]);
//        }
        //校验参数
        $rules = [
            ['fromid','require','10001'],
            ['toid','require','10001'],
            ['content','require','10001'],
            ['isread','require','10001'],
            ['type','require','10001'],
        ];
        $msg   = $this->validate($this->params, $rules);
        if ($msg !== true) $this->return_msg($msg, '参数错误');
        //过滤不必要的参数
        $safe_data = $this->getDataByRule($this->params, $rules);
        //存储聊天记录
        $communicationModel = new CommunicationModel();
        $res = $communicationModel->add($safe_data);
        if(!$res){
            $this->return_msg("20001","添加聊天记录失败",[]);
        }else{
            $this->return_msg("00000","添加聊天记录成功",[]);
        }
    }

    /***
     * Desc :获取聊天记录
     * User : HAIYUN
     * Date : 2022-01-17 17:31
     */
    public function getMessage()
    {
        //校验参数
        $rules = [
            ['fromid','require','10001'],
            ['toid','require','10001'],
        ];
        $msg   = $this->validate($this->params, $rules);
        if ($msg !== true) $this->return_msg($msg, '参数错误');
        //查询聊天记录
        $fromid = $this->params['fromid'];
        $toid = $this->params['toid'];
        $communicationModel = new CommunicationModel();
//        $where = [
//            'fromid'=>$fromid,
//            'toid'=>$toid,
//        ];
//        $where_or = [
//            'fromid'=>$toid,
//            'toid'=>$fromid,
//        ];
//        $messages = $communicationModel->where($where)->whereOr($where_or)->order('id')->select();
        $messages = $communicationModel->where('(fromid=:fromid&&toid=:toid)||(fromid=:fromid2&&toid=:toid2)',['fromid'=>$fromid,'toid'=>$toid,'fromid2'=>$toid,'toid2'=>$fromid])->order('id')->select();
        $this->return_msg('00000','查询聊天页面成功',$messages);
    }


    /***
     * Desc:上传聊天图片
     * User: HAIYUN
     * Date: 2022/2/27 10:30
     */
    public function uploadCommunicationImg() {
        $url = config('setting.communication_img_url');
        $type = 'communication';
        $this->img_upload($url,$type);
    }


    /***
     * Desc:获取聊天列表
     * User: HAIYUN
     * Date: 2022/3/1 14:10
     */
    public function getCommunicationList() {
          //获取用户
        //根据token获取uid
        $uid = $this->getCurrentTokenVar("uid");
        //根据uid查找用户数据，判断是否存在
        $userModel = new UserModel();
        $user = $userModel->where("id",$uid)->find();
        if(!$user){
            $this->return_msg("20004","用户不存在",[]);
        }
//        $toid = 13;//toid,接收消息的一方
        $communicationModel = new CommunicationModel();
//        $data = $communicationModel->field(['fromid','toid'])->where(['toid'=>$uid])->group('fromid')->select();
//        $data = $communicationModel->field(['fromid','toid'])->where(['toid'=>$uid])->whereOr(['fromid'=>$uid])->group('fromid')->select();

        $data = $communicationModel->field(['toid','fromid'])->where(['fromid'=>$uid])->group('toid')
            ->union('SELECT `fromid` AS `toid`,`toid` AS `fromid`
                            FROM `tb_communication`
                            WHERE `toid` = ' . $uid.'
                            GROUP BY `fromid`')->select();
        $return_data = [];
        //获取最新的一条聊天记录
        foreach ($data as $k => $v){
            $fromid = $v['fromid'];
            $toid = $v['toid'];
            $info = $communicationModel->where('(fromid=:fromid&&toid=:toid)||(fromid=:fromid2&&toid=:toid2)',['fromid'=>$fromid,'toid'=>$toid,'fromid2'=>$toid,'toid2'=>$fromid])->order('id desc')->find();
//            $return_data[$k] = $info;
            //判断谁是发送者
            $new_from_id = $info['fromid'];
            if($new_from_id == $uid){//自己为最后消息发送者,展示toid信息
                $return_data[$k]['fromid'] = $info['toid'];
                $return_data[$k]['toid'] = $new_from_id;
                $user_info = $userModel->where(['id'=>$info['toid']])->find();
                $return_data[$k]['nick_name'] = $user_info['nick_name'];
                $return_data[$k]['avater'] = $user_info['avater'];
            }else{//对方为最后消息发送者
                $return_data[$k]['fromid'] = $info['fromid'];
                $return_data[$k]['toid'] = $info['toid'];
                $return_data[$k]['nick_name'] = $info->user->nick_name;
                $return_data[$k]['avater'] = $info->user->avater;
            }
            $return_data[$k]['not_read'] = $this->getCountNotRead($info['fromid'],$info['toid']);
            $return_data[$k]['last_message'] = $info['content'];
            $return_data[$k]['last_time'] = $info['create_time'];
            unset($data[$k]['user']);
        }

//        for($i=0; $i < count($data); $i++){
//            $fromid = $data[$i]['toid'];
//            $data[$i]['nick_name']  = $data[$i]->user->nick_name;
//            $data[$i]['avater']  = $data[$i]->user->avater;
//            $data[$i]['not_read'] = $this->getCountNotRead($fromid,$uid);
//            $data[$i]['last_message'] = $this->getLastMessage($fromid,$uid)['content'];
//            $data[$i]['last_time'] = $this->getLastMessage($fromid,$uid)['create_time'];
//            unset($data[$i]['user']);
//        }
        //获取自己给别人发的
        $this->return_msg('00000','获取聊天列表成功',$return_data);
    }

    /***
     * Desc: 根据fromid,toid获取未读信息
     * User: HAIYUN
     * Date: 2022/3/1 14:44
     */
    private function getCountNotRead($fromid,$toid) {
        $communicationModel = new CommunicationModel();
        $where = [
            'fromid' => $fromid,
            'toid' => $toid,
            'isread' => 0,
        ];
        $count = $communicationModel->where($where)->count('id');
        return $count;
    }

    /***
     * Desc:获取最后一条聊天数据
     * User: HAIYUN
     * Date: 2022/3/1 14:56
     */
    private function getLastMessage($fromid,$toid) {
        $communicationModel = new CommunicationModel();
        $info = $communicationModel->where('(fromid=:fromid&&toid=:toid)||(fromid=:fromid2&&toid=:toid2)',['fromid'=>$fromid,'toid'=>$toid,'fromid2'=>$toid,'toid2'=>$fromid])->order('id DESC')->limit(1)->find();
        return $info;
    }

    /***
     * Desc:修改消息状态(未读->已读)
     * User: HAIYUN
     * Date: 2022/3/1 16:44
     */
    public function changeNoRead() {
        //校验参数
        $rules = [
            ['fromid','require','10001'],
            ['toid','require','10001'],
        ];
        $msg   = $this->validate($this->params, $rules);
        if ($msg !== true) $this->return_msg($msg, '参数错误');
        $communicationModel = new CommunicationModel();
        $communicationModel->edit(['isread'=>1],['fromid'=>$this->params['toid'],'toid'=>$this->params['fromid']]);
        $this->return_msg('00000','更新消息状态成功',[]);
    }
}